package com.etong.frame.directive.checker.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.etong.frame.directive.checker.Checker;
import com.etong.frame.directive.checker.CheckerConfig;
import com.etong.frame.directive.checker.CheckerFactory;
import com.etong.frame.directive.checker.CheckerGroup;

public class CheckerFactoryImpl implements CheckerFactory {

	Logger logger = LoggerFactory.getLogger(CheckerFactoryImpl.class);

	private final static String KEY_CHECKER_EXPR = "checker_expr";
	private final static String KEY_CHECKER_CODE = "checker_code";
	private final static String KEY_CHECKER_TOAST = "checker_toast";

	public CheckerImpl createChecker(String expr) {
		logger.info("Create checker :" + expr);

		CheckerImpl checker = null;
		if (expr.startsWith("@Size(")) {
			checker = new Size();
		} else if (expr.startsWith("@Length(")) {
			checker = new Length();
		} else if (expr.startsWith("@Null")) {
			checker = new Null();
		} else if (expr.startsWith("@NotNull")) {
			checker = new NotNull();
		} else if (expr.startsWith("@Max")) {
			checker = new Max();
		} else if (expr.startsWith("@Min")) {
			checker = new Min();
		} else if (expr.startsWith("@Value")) {
			checker = new Value();
		}

		if (!checker.build(expr)) {
			logger.error("Build checker error :" + expr);
			return null;
		}

		return checker;
	}

	public CheckerGroup createChecker(CheckerConfig checkerConfig) {
		CheckerGroup checkerGroup = new CheckerGroup();
		checkerGroup.setGroupName(checkerConfig.getName());
		checkerGroup.setCheckerConfig(checkerConfig);

		// 通过配置创建检查器
		for (Map<String, Object> checkerMap : checkerConfig.getCheckerMaps()) {
			checkerGroup.addChecker(createChecker(checkerMap));
		}
		return checkerGroup;
	}

	private Checker createChecker(Map<String, Object> checkerMap) {
		String expr = (String) checkerMap.get(KEY_CHECKER_EXPR);
		CheckerImpl checker = createChecker(expr);

		if (null != checker) {
			Integer checkerCode = (Integer) checkerMap.get(KEY_CHECKER_CODE);
			String checkerToast = (String) checkerMap.get(KEY_CHECKER_TOAST);

			checker.setCode(checkerCode);
			checker.setToast(checkerToast);
		}
		return checker;
	}
}
